package com.mobile.wizardForm.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.mobile.wizardForm.util.ProgressInfo;

public class FileUploadServlet extends HttpServlet {

	
	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(final HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//request.setCharacterEncoding("gb2312") ;
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);

		// 创建一个磁盘文件工厂
		FileItemFactory factory = new DiskFileItemFactory();

		// 创建一个新的文件处理器
		
		try {
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			
			ProgressListener progressListener = new ProgressListener() {
				private long megaBytes = -1;

				public void update(long pBytesRead, long pContentLength, int pItems) {
					
					long mBytes = pBytesRead / 1000000;
					if (megaBytes == mBytes&&pBytesRead!=pContentLength) {
						return;
					}
					megaBytes = mBytes;
					System.out.println("We are currently reading item " + pItems);
					System.out.println(pBytesRead+">>"+pContentLength+">>>" + pItems);

					if (pContentLength == -1) {
						/*System.out.println("So far, " + pBytesRead
								+ " bytes have been read.");*/
						return;
					} else {
						setSession(pBytesRead,pContentLength, pItems,request);
					}
				}
			};
			
			upload.setProgressListener(progressListener);
			/*
			 *解析request时就上传文件 
			 */
			List<FileItem> items = upload.parseRequest(request);
						
			for (FileItem item : items) {
				if (item.isFormField()) {
					//processFormField(item);
				} else {
					// processUploadedFile(item);
					String fieldName = item.getFieldName();
					String fileName = item.getName();
					if(fileName.lastIndexOf("\\")!=-1){
						fileName = fileName.substring(fileName.lastIndexOf("\\"));
					}
					File file = new File("f:" + File.separator + fileName);
					item.write(file);
				}
			}

		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.flush();
		out.close();
	}
	/**
	 * 把过程百分比放置到session的procss参数中,procss是个Map对象
	 * @param pBytesRead				已经读取的数据
	 * @param pContentLength			文件的总大小
	 * @param pItems					表单中的第几个字段
	 * @param request					请求对象
	 */
	public void setSession(long pBytesRead, long pContentLength, int pItems,HttpServletRequest request){
		NumberFormat format = new DecimalFormat("#0.00");
		NumberFormat formatPer = new DecimalFormat("#");
		
		double a = pBytesRead;
		double b = pContentLength;

		double d = Double.valueOf(format.format(a / b));
		double dPer=Double.valueOf(formatPer.format((a / b)*100));
		
		ProgressInfo progressInfo=new ProgressInfo(d,String.valueOf(dPer)+"%");
		
		String formIdex=String.valueOf(pItems);
		
		Map<String,ProgressInfo> map=(HashMap<String,ProgressInfo>)request.getSession().getAttribute("procss");
		if(map==null){
			Map<String,ProgressInfo> procssMap=new HashMap<String,ProgressInfo>();
			if(pItems==0){
				return;
			}
			procssMap.put(formIdex, progressInfo);
			
			request.getSession().setAttribute("procss", procssMap);
		}else{
			map.put(formIdex, progressInfo);
		}
		
		
		
		/*System.out.println("So far, " + pBytesRead + " of "
				+ pContentLength + " bytes have been read." + progressInfo.getValue()+">>>>"+progressInfo.getText());*/
	}
	
}
